package com.iwe3.protal.service;

import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.iwe3.protal.common.PageResult;
import com.iwe3.protal.entity.BookEntity;
import com.iwe3.protal.mapper.BookMapper;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.BoundZSetOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class BookServiceImpl implements IBookService{

    private final BookMapper bookMapper;
    private final RedisTemplate redisTemplate;

    public BookServiceImpl(BookMapper bookMapper,@Qualifier("redisTemplate")RedisTemplate redisTemplate) {
        this.bookMapper = bookMapper;
        this.redisTemplate = redisTemplate;
    }

    @Override
    public Page<BookEntity> listAllByTypeId(Integer typeId, Integer currentPage, Integer currentSize) {
        return PageHelper.
                startPage(currentPage,currentSize)
                .doSelectPage(() -> bookMapper.findAllByTypeId(typeId));
    }

    @Override
    public BookEntity getById(Long id) {
        return bookMapper.getById(id);
    }

    @Override
    public List<BookEntity> list2Top10() {
        BoundZSetOperations bzo=redisTemplate.boundZSetOps("book10");
        if(!redisTemplate.hasKey("booktop10")){
            List<BookEntity> all=bookMapper.findAll();
            all.forEach(e->bzo.add(e,e.getCollectioncount()));
        }
        Set<LinkedHashMap> set =bzo.reverseRange(0,9);
        return set.stream().map(e->{
            String s= JSONUtil.toJsonStr(e);
            return JSONUtil.toBean(s, BookEntity.class);
        }).collect(Collectors.toList());



    }
}
